package com.rimi.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.rimi.bean.Page;
import com.rimi.bean.Shop;
import com.rimi.bean.Shopcar;
import com.rimi.service.ShopService;
import com.rimi.service.ShopcarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;

/**
 * @program: ECsystem
 * @Date: 2018/9/17 19:01
 * @Author: Mr.GuoQiang
 * @Description:
 */
@Controller
@SessionAttributes({"shop","num","shopcarList","sumMoney"})
public class ShopController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopcarService shopcarService;

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/search")
    public void index(Model model, HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //查询条件对象
        Shop shop = new Shop();
        //分页对象
        Page page=new Page();
        //从request请求中获取到分页信息
        String nowPage = request.getParameter("nowPage");
        String pageSize = request.getParameter("pageSize");
        System.out.println("nowPage="+nowPage+"---pageSize="+pageSize);
        //将信息封装到对象中
        if(nowPage!=null&&!"".equals(nowPage)){
            page.setNowPage(Integer.parseInt(nowPage));
        }

        if (pageSize!=null&&!"".equals(pageSize)){
            page.setPageSize(Integer.parseInt(pageSize));
        }
        List<Shop> shopList = shopService.getShopList(shop, page);

        //request.setAttribute("shopList",shopList);
        //请求转发
//      request.getRequestDispatcher("list.jsp").forward(request,response);

        //前后端分离  JSON格式的字符串进行传值  Gson  Json  FastJson  ali
        //使用fastjson将集合转换为json字符串
        String json = JSONObject.toJSONString(shopList);
        //System.out.println(json);
        //获取到输出流对象
        PrintWriter writer = response.getWriter();
        //
        writer.append(json);
        writer.flush();
    }


    @RequestMapping("/successCart")
    public String successCart(Model model,HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("utf-8");

        String id = request.getParameter("id");
        int i = Integer.parseInt(id);
        String number = request.getParameter("num");
        int num = Integer.parseInt(number);

        Shop shop = shopService.getShopById(i);
        System.out.println(shop);
        //加入购物车
        Shopcar shopcar = new Shopcar();
        shopcar.setShopid(shop.getId());
        shopcar.setShopname(shop.getName());
        shopcar.setPrice(shop.getPrice());
        shopcar.setNumber(num);
        shopcar.setSize(shop.getSize());
        shopcar.setDetailed(shop.getDetailed());

        //1.查询该商品在购物车是否存在
        Shopcar shopcar1 = shopcarService.selectByShopId(shop.getId());
        if (shopcar1 == null){
            System.out.println("商品不在购物车");
            int i2 = shopcarService.insert(shopcar);
            if (i2 > 0){
                System.out.println("加入购物车成功");
            }
        }else {
            //改变数量
            shopcar.setNumber(num+shopcar1.getNumber());
            shopcar.setId(shopcar1.getId());
            int i3 = shopcarService.updateByPrimaryKey(shopcar);
            if (i3 > 0){
                System.out.println("更新购物车成功");
            }
        }


        model.addAttribute("shop",shop);
        model.addAttribute("num",num);

        return "success-cart";
    }

    @RequestMapping("/item")
    public String item(Model model,HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        int i = Integer.parseInt(id);
        Shop shop = shopService.getShopById(i);
        model.addAttribute("shop",shop);
        return "item";
    }

    @RequestMapping("/cart")
    public String cart(Model model){
        List<Shopcar> shopcarList = shopcarService.selectByExample();
        System.out.println(shopcarList);
        model.addAttribute("shopcarList",shopcarList);
        return "cart";
    }

    @RequestMapping("/changeNum")
    public String changeNum(Model model,HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");

        String shopid = request.getParameter("shopid");
        int i = Integer.parseInt(shopid);
        String number = request.getParameter("num");
        int num = Integer.parseInt(number);

        //更新购物车
        Shopcar shopcar = shopcarService.selectByShopId(i);
        //改变数量
        shopcar.setNumber(shopcar.getNumber()+num);

        if (shopcar.getNumber()+num < 0){
            return "redirect:/cart";
        }

        int i2 = shopcarService.updateByPrimaryKey(shopcar);
        if (i2 > 0){
            System.out.println("更新购物车成功");
        }

        List<Shopcar> shopcarList = shopcarService.selectByExample();
        model.addAttribute("shopcarList",shopcarList);

        return "redirect:/cart";
    }


    @RequestMapping("/delShopCar")
    public String delShopCar(Model model,HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        int i = Integer.parseInt(id);
        int i1 = shopcarService.deleteByPrimaryKey(i);
        if (i1 > 0){
            System.out.println("购物车删除成功");
        }
        List<Shopcar> shopcarList = shopcarService.selectByExample();

        model.addAttribute("shopcarList",shopcarList);

        return "redirect:/cart";
    }

    @RequestMapping("/delAllCart")
    public String delAllCart(Model model) throws IOException {
        int i1 = shopcarService.deleteByExample();
        if (i1 > 0){
            System.out.println("购物车清空成功");
            return "redirect:/search.jsp";
        }
        return null;
    }


    @RequestMapping("/sumMoney")
    public void sumMoney(Model model, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        System.out.println("---sumMoney---");

        List<Shopcar> shopcarList = shopcarService.selectByExample();

        double sumMoney = 0;
        for (Shopcar shopcar : shopcarList) {
            String s = shopcar.getPrice().toString();
            double price = Double.parseDouble(s);
            sumMoney = sumMoney + price * shopcar.getNumber();
        }

        System.out.println("sumMoney"+sumMoney);
        response.getWriter().append("ajax回调成功，获取到总金额");

        model.addAttribute("sumMoney",sumMoney);

    }

    @RequestMapping("/pay")
    public String pay(Model model){
        List<Shopcar> shopcarList = shopcarService.selectByExample();
        System.out.println(shopcarList);
        model.addAttribute("shopcarList",shopcarList);
        return "getOrderInfo";
    }


    @RequestMapping("/Alipay")
    public void Alipay(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String sum = request.getParameter("sum");


        //https://openapi.alipay.com/gateway.do
        String serverUrl="https://openapi.alipaydev.com/gateway.do";
        String APP_ID="2016091600525932";
        String APP_PRIVATE_KEY="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCimnoZedJEFwHYEYX4or/OBp+dwZMKaB6lO2PYbogyobWldnoGVB7TeAaXYROvHSQs/zCvRcEnvUX8ChEts/X2e96WLwePVlbV/WtrqFIn917eTaDaEe2fHa5AkenixKlHih6iTQAIt0SYfiybX05m4q8vUhpOYXD0/a0/U0vBSeF+uioEf7j5FK9kTjXO4MRBczqUK2Fw+4AzFVr1hY+dUnQsuyR0FlZkZC/V8b76YN4voiaP8ZGgCYlzBM2wnQQzDQe1wMsAmiMj8UjWWApC/Vx6+7xOD9P8Z7TLzZy6mFfqB4agPTO1TY8ooH8pP3nfEMlftqeku6mDtwDn4QyDAgMBAAECggEAD7UylGFzUYaTdAcFVSaLtuBm7Pt1M+0pALdDBvZui82ZWZmfYhsgOzd+E4OaPjFnfD1Ou6/WX/tl1lo2nJ6k5SHEN+flKBCkJNntVaIWBaxc6sa/AjH3LYbVfYFbAcATxkhueylLFox1wPF3Z68GSOQfHkglKGs7WT9kTBjE2bAcvKq6zEvy0+inhx54hXHhrOY0u6jlv9nWq3oc0A78zekq2gVhA1yT6YTqvhPt0S6dFyEVVb8EoJ+KRauqkvdpKMea1QbdOSUhJeh20lC2lyYY/Hrn+kK+OMpPGsBzJKJvCx0agVe49V6T5w0AAanV2afg/9nAo2oYUUnlEXA0AQKBgQDlCAfVwEk6rY/U9qbIsojXFb0KrKwL1PLhYHeXSzMO4ZSzTuimCD6JIBP08L8nXCXhKKyrQw8F+V/TkHrvPNAzfDpG27i1hNlTg+m9uqGdG+7ok1UBKKkISo0Bou+wclZKXHUZEZKseTEa8loaFe6urrFBmKQscbgFYyMpskuuAQKBgQC1wAdOhgMs0oPdeF6dmMn9zH1jtUp31Bg1JpxMAihA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7anpLupg7cA5+EMgwIDAQAB";
        String SIGN_TYPE="RSA2";

        Random random = new Random();
        String rand = random.nextInt(9000)+1000 +"";

        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,
                APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:8002/delAllCart");//支付成功后跳转的地址
        alipayRequest.setNotifyUrl("https://www.baidu.com");//在公共参数中设置回跳和通知地址  //异步访问
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"2015032001010"+rand+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+sum+"," +
                "    \"subject\":\"订单支付\"," +
                "    \"body\":\"订单支付\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + CHARSET);
        //直接将完整的表单html输出到页面
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();


    }
}
